package net._7colorlotus.gateway.routerPredicateFactory;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义谓词断言
 *
 * 设定header里必须有指定的key和value
 *
 * MyHeader 为谓词的key
 * MyConfig 指定谓词的值，MyConfig是key,value
 *
 *
 */
@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<MyConfig> {

    public MyHeaderRoutePredicateFactory(){
        super(MyConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyConfig config) {

        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //从请求头中获取Key对应的值value
                String value = serverWebExchange.getRequest().getHeaders().getFirst(config.getKey());
                if(StringUtils.isEmpty(value)){
                    return false;
                }
                if(value.equalsIgnoreCase(config.getValue())){
                    return true;
                }
                return false;
            }
        };
    }

    /**
     * -MyHeader=name,xxx
     * name --> Myconfig.key
     * xxx  --> Myconfig.value
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("key", "value");
    }
}
